// 2017年12月5日

let TodoList = React.createClass({
    render: function () {
        let createItem = function (itemText) {
            return <li>{itemText}</li>;
        };
        return <ul>{this.props.items.map(createItem)}</ul>;
    }
});
let TodoApp = React.createClass({
    getInitialState: function () {
        return { items: ['a', 'b'], text: '' };
    },
    onChange: function (e) {
        this.setState({ text: e.target.value });
    },
    handleEnter: function (e) {
        console.log(e.keyCode);
        let keyCode = null;
        
        if (e.which) {
            keyCode = e.which;
        }
        else if (e.keyCode) {
            keyCode = e.keyCode;
        }
        if (keyCode && keyCode == 13) {
            return this.handleSubmit(e);
        }
    },
    handleSubmit: function (e) {
        e.preventDefault();  // 防止点击之后刷新页面。
        let nextItems = this.state.items.concat([this.state.text]);
        let nextText = '';
        this.setState({ items: nextItems, text: nextText });        
    },
    render: function () {
        return (
            <div>
                <h3>TODO</h3>
                <TodoList items={this.state.items} />
                {/* <form onSubmit={this.handleSubmit}> */}
                <input onChange={this.onChange} onKeyUp={this.handleEnter} value={this.state.text} placeholder="请输入..." />
                <button onClick={this.handleSubmit}>{'添加第#' + (this.state.items.length + 1) + '个条目'}</button>
                {/* </form> */}
            </div>
        );
    }
});
React.render(<TodoApp />, document.getElementById("todo"));